import {Code, CodeError, Http, HttpBuilder} from "mvx-foundation";

const request = async (options: UniNamespace.RequestOptions):Promise<[UniNamespace.RequestSuccessCallbackResult|undefined, Error|null]> => {
  return new Promise(resolve => {
    options.success = (result) => {
      resolve([result, null])
    };

    options.fail = (err) => {
      resolve([undefined, new Error(err.errMsg)])
    };
    uni.request(options)
  })
};

export class WXHttp implements Http {
  async send(): Promise<[string, CodeError]> {
    let headers:Record<string, string> = {};
    this.builder.headers().forEach(((value, key) => {
      headers[key] = value;
    }));


    const url = this.builder.getUrl();
    console.log(`${url} req `, this.builder.content());
    if (this.enableRealtimeLog) {
      uni.getRealtimeLogManager().info([`${url} req `, this.builder.content()]);
    }

    const [ret, err] = await request({
      url:url,
      method:<any>this.builder.method(),
      header:headers,
      data:this.builder.content(),
      dataType:"其他",
      responseType:"text",
    });

    console.log(`${url} res `, ret);
    if (this.enableRealtimeLog) {
      uni.getRealtimeLogManager().info([`${url} res `, ret]);
    }

    if (err) {
      return [JSON.stringify({}), new CodeError(err.message, Code.ElseError)]
    }

    return [<string>ret?.data??JSON.stringify({}), new CodeError(`code is ${ret?.statusCode}`, ret?.statusCode)];
  }

  constructor(private builder: HttpBuilder,  private enableRealtimeLog = false) { }
}